package com.anxin.service.impl;

import cn.hutool.core.util.IdUtil;
import com.anxin.common.enums.RoleEnum;
import com.anxin.entity.PatientInfo;
import com.anxin.entity.SysUser;
import com.anxin.mapper.SysUserMapper;
import com.anxin.service.PatientInfoService;
import com.anxin.service.SysUserService;
import com.anxin.system.dto.RegisterDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    private PatientInfoService patientInfoService;

    @Autowired
    public SysUserServiceImpl(SysUserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public SysUser getByUsername(String username) {
        return userMapper.getByUsername(username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLoginInfo(String userId, String ip) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setLastLoginTime(LocalDateTime.now());
        user.setLastLoginIp(ip);
        user.setLoginFailCount(0);
        userMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void lockUser(String userId) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setStatus(0);
        user.setLockedTime(LocalDateTime.now());
        userMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unlockUser(String userId) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setStatus(1);
        user.setLockedTime(null);
        user.setLoginFailCount(0);
        userMapper.updateById(user);
    }

    @Override
    public List<String> getUserRoles(String userId) {
        return userMapper.getUserRoles(userId);
    }

    @Override
    public List<String> getUserPermissions(String userId) {
        return userMapper.getUserPermissions(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (getByUsername(registerDTO.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }

        String uuid = IdUtil.getSnowflakeNextIdStr();

        // 创建新用户
        SysUser user = new SysUser();
        user.setId(uuid);
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setRealName(registerDTO.getRealName());
        user.setRoleId(RoleEnum.PATIENT.getCode()); // 默认为普通用户角色
        user.setPhone(registerDTO.getPhone());
        user.setEmail(registerDTO.getEmail());
        user.setStatus(1);
        user.setLoginFailCount(0);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        //写入患者详细信息
        PatientInfo patientInfo = new PatientInfo();
        patientInfo.setId(IdUtil.getSnowflakeNextIdStr());
        patientInfo.setUserId(uuid);
        patientInfo.setRealName(registerDTO.getRealName());
        patientInfo.setPhone(registerDTO.getPhone());
        patientInfo.setEmail(registerDTO.getEmail());
        patientInfoService.save(patientInfo);

        // 保存用户
        userMapper.insert(user);
    }

    @Override
    public Page<SysUser> page(int pageNum, int pageSize, String username, String realName, String phone, Integer status) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(username), SysUser::getUsername, username)
                .like(StringUtils.hasText(realName), SysUser::getRealName, realName)
                .like(StringUtils.hasText(phone), SysUser::getPhone, phone)
                .eq(status != null, SysUser::getStatus, status)
                .orderByDesc(SysUser::getCreateTime);

        return page(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public List<SysUser> getAllUsers() {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(SysUser::getCreateTime);
        return list(wrapper);
    }

    @Override
    public SysUser findByUsername(String username) {
        return userMapper.getByUsername(username);
    }
}
